package matrixCalculator;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

import Jama.Matrix;


/** 
 * This is the main class of the Third implementation for the matrix calculator.
 * Here the connections are created and stored in a queue so they can all be attended correctly. (requestQueue)
 * 
 * A MatrixOperationBuffer Vector is used to store the different operations requested
 * A MatrixResultsBuffer Vector is used to store the answers that are generated by the different threads.
 * 
 * **/
public class MatrixCalculatorThirdImplementation implements matrixCalculatorServerInterface{

	int serverPort;
	DataOutputStream out;
	DataInputStream in;
	public static Vector <Socket> requestQueue= new Vector <Socket> ();
	public Vector<MatrixOperation> MatrixOperationBuffer = new Vector<MatrixOperation>();
	public Vector<MatrixOperation> MatrixResultsBuffer = new Vector<MatrixOperation>();

	public MatrixCalculatorThirdImplementation(String port){
		serverPort = Integer.parseInt(port);
		
	}

	@Override
	public  Matrix generatematrix(int size) {
		return MatrixHelper.generateMatrix(size);
	}

	@Override
	public Matrix saveToDisk() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Matrix getMatrixFromFile() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Matrix operation(Matrix a, Matrix b, String operator) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void SendResult(Matrix r) {
		// TODO Auto-generated method stub

	}

	@Override
	public void listenConnections() {

		try{			
			
			ConnectionsHandleObject connectionHandle= new ConnectionsHandleObject(MatrixOperationBuffer,MatrixResultsBuffer);
			connectionHandle.start();
			ServerSocket listenSocket = new ServerSocket(this.serverPort);
				while(true) {
					Socket clientSocket = listenSocket.accept();
					requestQueue.add(clientSocket);
				}				
				/*	
				if(MatrixResultsBuffer.firstElement().getR()!=null){
					
					MatrixOperation firstElement = MatrixResultsBuffer.remove(0);
					SendResult(firstElement.getR());					
					
				}*/			
		} catch(IOException e) {
			System.out.println("Listen socket:"+e.getMessage());
		}


	}

	@Override
	public MatrixOperation parseMessage(String request) {
		return null;
	}
	
	public static void main(String args[]){
		matrixCalculatorServerInterface matrixCalculator = new MatrixCalculatorThirdImplementation("7898");
		matrixCalculator.listenConnections();
	}

}
